package com.mnb.beidou.service;

import com.alibaba.fastjson.JSON;
import com.mnb.beidou.mapper.CusOrimesMapper;
import com.mnb.beidou.mapper.StPptnRMapper;
import com.mnb.beidou.mapper.StRiverRMapper;
import com.mnb.beidou.mapper.StStbprpBMapper;
import com.mnb.beidou.model.*;
import com.mnb.beidou.utils.CRC16Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class MessageService {

    private static final Logger logger = LoggerFactory.getLogger(MessageService.class);

    @Autowired
    private ModbusParser modbusParser;

    @Autowired
    private CusOrimesMapper cusOrimesMapper;

    @Autowired
    private StPptnRMapper stPptnRMapper;

    @Autowired
    private StRiverRMapper stRiverRMapper;

    @Autowired
    private StStbprpBMapper stStbprpBMapper;


    /**
     * 处理北斗设备上报的报文
     *
     * @param message 原始报文内容
     * @param topic   MQTT主题
     */
    @Transactional
    public void processMessage(String message, String topic) {
        ModbusDataEntity modbusDataEntity = new ModbusDataEntity();
        try {
            logger.info("开始处理北斗报文 - 主题: {}, 内容: {}", topic, message);
            CusOrimes cusOrimes = JSON.parseObject(message, CusOrimes.class);
            modbusDataEntity = modbusParser.parse(cusOrimes.getContent());

            String msgJson = null;
            if (modbusDataEntity != null && modbusDataEntity.getDataEntity() != null
                    && modbusDataEntity.getDataEntity().getMsgJson() != null) {
                msgJson = modbusDataEntity.getDataEntity().getMsgJson();
            }
            insertOriMessage(message, msgJson);

            String stcd = stStbprpBMapper.selectStcdByIdcard(cusOrimes.getFromCard());
            if (!StringUtils.isEmpty(stcd)) {
                cusOrimes.setStcd(stcd);
                insertStPptnR(cusOrimes, modbusDataEntity);
                insertStRiverR(cusOrimes, modbusDataEntity);
            }

        } catch (Exception e) {
            logger.error("处理北斗报文时发生错误", e);
            insertExOriMessage(message, e.getMessage());
        }
    }

    private void insertStRiverR(CusOrimes cusOrimes, ModbusDataEntity parse) {
        StRiverR stRiverR = new StRiverR();
        stRiverR.setStcd(cusOrimes.getStcd());
        stRiverR.setTm(cusOrimes.getTime());
        stRiverR.setZ(new BigDecimal(parse.getDataEntity().getRadarWaterLevel()));
        stRiverR.setQ(new BigDecimal(parse.getDataEntity().getInstantaneousFlow()));
        stRiverRMapper.insert(stRiverR);
    }

    private void insertStPptnR(CusOrimes cusOrimes, ModbusDataEntity parse) {
        StPptnR stPptnR = new StPptnR();
        stPptnR.setStcd(cusOrimes.getStcd());
        stPptnR.setTm(cusOrimes.getTime());
        stPptnR.setDrp(new BigDecimal(parse.getDataEntity().getCurrentRainfall()));
        stPptnRMapper.insert(stPptnR);
    }

    public CusOrimes insertOriMessage(String message, String msgJson) {
        CusOrimes cusOrimes = JSON.parseObject(message, CusOrimes.class);
        cusOrimes.setReceiveTm(new Date());
        cusOrimes.setStatus(0);
        cusOrimes.setMsgJson(msgJson);
        cusOrimesMapper.insert(cusOrimes);
        return cusOrimes;
    }

    public void insertExOriMessage(String message, String errorMsg) {
        CusOrimes cusOrimes = JSON.parseObject(message, CusOrimes.class);
        cusOrimes.setReceiveTm(new Date());
        cusOrimes.setStatus(1);
        cusOrimesMapper.insert(cusOrimes);
    }

} 